//
//  WebBrowserViewController.swift
//  App_Common_WebBrowser
//
//  Created by 蒋晨成 on 2022/1/19.
//

import App_Common_FoundationExtensions
import Chain
import SnapKit
import Toast
import UICore
import UIKit
import WebKit

class WebBrowserViewController: ViewController {
    private let url: URL
    private lazy var contentView = WebBrowserContentView(delegate: self)

    init(url: URL) {
        self.url = url
        super.init(nibName: nil, bundle: nil)
    }

    @available(*, unavailable)
    required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") }
}

// MARK: - Override

extension WebBrowserViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        setup()

        contentView.load(url: url)
    }
}

private extension WebBrowserViewController {
    func setup() {
        let image = UIImage(systemName: "arrow.left")
        let barButtonItem = UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(backAction))
        barButtonItem.tintColor = .label
        navigationItem.leftBarButtonItem = barButtonItem

        contentView.x.add(to: view).snp.makeConstraints {
            $0.leading.trailing.equalToSuperview()
            $0.top.equalTo(view.safeAreaLayoutGuide.snp.top)
            $0.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
        }
    }

    @objc
    func backAction() {
        navigationController?.popViewController(animated: true)
    }
}

extension WebBrowserViewController: WebBrowserContentView.Delegate {
    func contentView(_: WebBrowserContentView, webView _: WKWebView, urlDidChange _: URL?) {}

    func contentView(_: WebBrowserContentView, webView _: WKWebView, titleDidChange title: String?) {
        navigationItem.title = title
    }

    func contentView(_ contentView: WebBrowserContentView, webView _: WKWebView, estimatedProgressDidChange estimatedProgress: Double) {
        contentView.set(progress: Float(estimatedProgress))
    }

    func contentView(_: WebBrowserContentView, webView _: WKWebView, showAlert alertController: UIAlertController) {
        present(alertController, animated: true)
    }
}

extension WebBrowserViewController: Routable {
    class func initialize(values: [String: Any]) -> ViewController? {
        guard let urlEncodeString = values["url"] as? String,
              let urlString = urlEncodeString.urlDecode(),
              let url = URL(string: urlString)
        else {
            return nil
        }
        return WebBrowserViewController(url: url)
    }

    static let routePattern: String = "\(routeName)/<string:url>"
    static let description: String = "Web Browser"
}
